package com.zhu.algorithm.jzOffer.linkedList;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zhujiabao
 * @Date: 2023/01/27/21:28
 * @Description: JZ24 反转链表
 */
public class Solution24 {

    public static void main(String[] args) {
//        构建链表
        ListNode headNode = new ListNode(0);
        ListNode listNode = headNode;
        for (int i = 1; i < 10; i++) {
            listNode.next = new ListNode(i);
            listNode = listNode.next;
        }

        Solution24 Solution24 = new Solution24();

        Solution24.printLinklist(headNode);

        ListNode head = Solution24.ReverseList(headNode);

        Solution24.printLinklist(head);


    }

    // 打印链表
    public void printLinklist(ListNode HeadList) {
        ListNode listNode = HeadList;
        System.out.print("[ ");
        while (listNode != null) {
            System.out.print(listNode.val + ", ");
            listNode = listNode.next;
        }
        System.out.println(" ]");
    }

    // 反转链表
    public ListNode ReverseList(ListNode head) {
        ListNode headNode = head;
        ListNode listNode ;
        ListNode tempNode ;
        ListNode tailNode ;

        // 空链表和一个节点时
        if (headNode == null || headNode.next == null) {
            return headNode;
        }
        // 两个节点时
        if (headNode.next.next == null) {
            tempNode = headNode.next;
            tempNode.next = headNode;
            headNode.next = null;
            return tempNode;
        }
        // 两个以上节点时
        listNode = headNode.next.next;
        tempNode = headNode.next;
        tailNode = headNode;

        while (true) {
            if (listNode == null) {
                tempNode.next = tailNode;
                headNode.next = null;
                return tempNode;
            }
            tempNode.next = tailNode;
            tailNode = tempNode;
            tempNode = listNode;
            listNode = listNode.next;
        }
    }

}
